package cn.jluzh.blog.modules.category.controller;

import cn.jluzh.blog.commons.result.Result;
import cn.jluzh.blog.commons.result.ResultFactory;
import cn.jluzh.blog.modules.category.entity.SysCategory;
import cn.jluzh.blog.modules.category.service.impl.CategoryServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "分类相关接口")
@RequestMapping("category")
public class CategoryController {
    @Autowired
    CategoryServiceImpl categoryService;

    @GetMapping("getAllCategory")
    @ApiOperation("查询所有的分类")
    public Result getAllArticle(){
        List<SysCategory> allCategory = categoryService.getAllCategory();
        return ResultFactory.buildSuccessResult(allCategory);
    }

    @GetMapping("getAllCategoryByName")
    @ApiOperation("查询所有的分类")
    public Result getAllCategoryPage(@RequestParam(name="pageNo",defaultValue="1") Integer pageNo,
                                 @RequestParam(name="pageSize",defaultValue="10") Integer pageSize,
                                    @RequestParam(name="query", required=false) String query){
        PageHelper.startPage(pageNo, pageSize);
        List<SysCategory> allCategory;
        if(query!=null){
            allCategory=categoryService.getAllCategoryByName(query);
        }else {
            allCategory = categoryService.getAllCategory();
        }
        PageInfo<SysCategory> pageInfo = new PageInfo<>(allCategory);
        return ResultFactory.buildSuccessResult(pageInfo);
    }

    @GetMapping("getCategoryById")
    @ApiOperation("获取单个分类")
    public Result getTagById(@RequestParam(name="id",required=true) Integer id){
        SysCategory categoryById=categoryService.getCategoryById(id);
        return ResultFactory.buildSuccessResult(categoryById);
    }

    @PostMapping("updateCategory")
    @ApiOperation("修改分类信息")
    public Result updateCategory(@RequestBody SysCategory sysCategory){
        boolean b = categoryService.updateById(sysCategory);
        return ResultFactory.buildSuccessResult(b);
    }

    @PostMapping("addCategory")
    @ApiOperation("新增分类")
    public Result addCategory (@RequestBody SysCategory sysCategory){
        boolean b = categoryService.saveOrUpdate(sysCategory);
        return ResultFactory.buildSuccessResult(b);
    }

    @DeleteMapping("deleteCategory")
    @ApiOperation("删除分类")
    public Result deleteCategory(@RequestParam(name = "id") Integer id){
        boolean b = categoryService.removeById(id);
        return ResultFactory.buildSuccessResult(b);
    }

    @GetMapping("/categoryTotal")
    @ApiOperation("获取分类总量")
    public Result categoryTotal() {
        int count = categoryService.count();
        return ResultFactory.buildSuccessResult(count);
    }
}
